const UniPayService = require('./unipay.js')
const uniPay = require('uni-pay');
/**
 * 微信支付处理
 */
module.exports = class WxpayService extends UniPayService {
	constructor(ctx) {
		super(ctx)
		this.type = "wxpay";
		this.payname = "微信";
	}
	async prepay(userInfo) {
		return {
			key: this.type,
			icon: "icon_pay_wxpay",
			color: "#00aa00",
			name: this.payname,
			confirm: false
		}
	}
	/**
	 *  验证
	 *  https://uniapp.dcloud.io/uniCloud/unipay?id=%e6%94%af%e4%bb%98%e7%bb%93%e6%9e%9c%e9%80%9a%e7%9f%a5%e5%a4%84%e7%90%86
	 */
	async verify(config, event, next) {
		let uniPayIns = uniPay[config["uniPay"]](config);
		//如果验证失败，会抛出异常，成功才能进入下面
		let res = await uniPayIns.verifyPaymentNotify(event);
		console.log("uniPayIns.verifyPaymentNotify", res)
		res.type = this.type;
		res.platform = config.platform;
		//处理各类订单支付完成之后的回调res.pfx = fs.readFileSync(fullPath);
		let order = await next(res);
		console.log("余额支付完成后，回调逻辑", order);
		if (order && order.receivers) {
			console.log("开始调用分账", res, order.receivers)
			//订单需要分账，[重要]支付完成不能立即调用分账，使用定时器调用
			// await this.profitsharing(res, order.receivers);
			try {
				//可能是接口有变，现在必须单个添加接收方
				for (let i = 0; i < order.receivers.length; i++) {
					let receiver = order.receivers[i]
					let proResult = await uniPayIns.profitsharingaddreceiver({
						sub_mch_id: res.subMchId ? res.subMchId : (res.sub_mchid ? res.sub_mchid : res
							.sub_mch_id),
						receiver: JSON.stringify(receiver)
					})
					//这里重复添加也没关系，只是提示已添加
					console.log("添加分账方完成", proResult)
				}
			} catch (e) {
				console.log("添加分账方错误", e.message)
			}
		}
		//返回成功字符串
		return this.returnNotifyData();
	}
	/**
	 * 服务商添加分账方https://pay.weixin.qq.com/wiki/doc/api/allocation_sl.php?chapter=25_3&index=4
	 * @param {Object} config
	 * @param {Object} event
	 * @param {Object} next
	 */
	async profitsharingaddreceiver(payment) {
		let config = await this.ctx.getConfigs.paymentConfigs(this.type);
		let receivers = {
			type: "MERCHANT_ID",
			account: config.mchId,
			name: config.accountName,
			relation_type: "SERVICE_PROVIDER"
		}
		/* Object.assign(config, {
			...payment
		}) */
		console.log("config", config, receivers)
		let uniPayIns = uniPay[config["uniPay"]](config);
		try {
			let proResult = await uniPayIns.profitsharingaddreceiver({
				sub_mch_id: payment.sub_mch_id,
				receiver: JSON.stringify(receivers)
			})
			/* {
			  receiver: '{"type":"MERCHANT_ID","account":"1604863346","relation_type":"SERVICE_PROVIDER"}',
			  sign: '29A97D386EF9EC5F5FA431BAE7D25C557A1B34BB208F55C2D16D11DD8D0D3787',
			  returnCode: 'SUCCESS',
			  resultCode: 'SUCCESS',
			  mchId: '1604863346',
			  subMchId: '1618544069',
			  nonceStr: 'bdcc26a214017e26',
			  appId: 'wxcfb12cd3b92a58ed',
			  returnMsg: 'ok',
			  errMsg: 'payment.profitsharingaddreceiver ok'
			} */
			console.log("profitsharingaddreceiver", proResult)
			return proResult;
		} catch (e) {
			//TODO handle the exception
			console.log(e)
			return {
				code: -1,
				message: e.message
			}
		}
	}
	async profitsharingorderamountquery(payment) {
		let config = await this.ctx.getConfigs.paymentConfigs(this.type);
		// config.mchId = payment.subMchId;
		let uniPayIns = uniPay[config["uniPay"]](config);
		try {
			let proResult = await uniPayIns.profitsharingorderamountquery({
				transactionId: payment.transactionId
			})
			console.log("profitsharingorderamountquery", proResult)
			return proResult.unsplitAmount;
		} catch (e) {
			//TODO handle the exception
			console.log(e)
		}
		return 0
	}
	/**
	 * 服务商分账https://pay.weixin.qq.com/wiki/doc/api/allocation_sl.php?chapter=25_1&index=1
	 * @param {Object} config
	 * @param {Object} event
	 * @param {Object} next
	 */
	async profitsharing(payment, receivers, callback) {
		console.log("进入分账", payment, receivers)
		let config = await this.ctx.getConfigs.paymentConfigs(this.type, payment.platform);
		let uniPayIns = uniPay[config["uniPay"]](config);
		try {
			console.log("开始分账", {
				subMchId: payment.subMchId,
				transactionId: payment.transactionId,
				outOrderNo: "p_" + Date.now(),
				receivers: JSON.stringify(receivers)
			})
			let proResult = await uniPayIns.profitsharing({
				subMchId: payment.subMchId,
				transactionId: payment.transactionId,
				outOrderNo: "p_" + Date.now(),
				receivers: JSON.stringify(receivers)
			})
			console.log("分账结束", proResult)
			await callback({
				profitsharing: proResult
			});
		} catch (e) {
			//TODO handle the exception
			console.log(e)
			return {
				code: -1,
				message: e.message
			}
		}

	}

	/**
	 * 微信企业转账到微信零钱，开通此功能需要特殊的要求
	 * @param {Object} data {amount,_id,user}
	 * @param {string} platform 平台
	 * https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2
	 */
	async transfers(data, platform, desc) {
		console.log("transfers", platform, desc)
		//前端登录配置，获得的openid才能对应
		let transferConfig = await this.ctx.getConfigs.paymentConfigs("weixin", "transfers");
		if (data.user && data.user.appid) {
			//必须保证appid与openid匹配
			transferConfig.appId = data.user.appid;
		}
		// console.log("config", transferConfig)
		let uniPayIns = uniPay["initWeixin"](transferConfig);
		let openid = this.getOpenid(data.user, platform)
		console.log("transfers", data)
		try {
			const result = await uniPayIns.transfers({
				amount: data.amount, //单位分
				desc,
				openid,
				partner_trade_no: data._id,
				check_name: "NO_CHECK",
			})
			console.log("transfers", result)
			result.code = 0;
			return result;
		} catch (e) {
			//TODO handle the exception
			console.log(e)
			return {
				code: -1,
				message: e.message
			}
		}
		return false;
	}
	/**
	 * 返回给微信服务器
	 */
	returnNotifyData() {
		return {
			header: "text/xml;charset=utf-8",
			result: "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>"
		}
	}

	getOpenid(userInfo, platform) {
		if (!platform) {
			platform = this.ctx.context.PLATFORM;
		}
		if (userInfo.wx_openid) {
			return userInfo.wx_openid[platform];
		}
		return false;
	}
}
